<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片项 -->
    <el-card class="box-card">
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        :closable="false"
        center
      >
      </el-alert>
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addFormData"
        :rules="addFormDataRule"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabclicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addFormData.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addFormData.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addFormData.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addFormData.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 商品类别级联选择器 -->
              <el-cascader
                v-model="addFormData.goods_cat"
                :options="cateList"
                :props="cateListProps"
                size="mini"
                clearable
                @change="handlleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 根据动态参数条目 循环创建表单项 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in params"
              :key="index"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(tab, index) in item.attr_vals"
                  :label="tab"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 根据静态属性条目 循环创建表单项 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in onlyTableData"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
              <!-- 富文本编辑器组件 -->
              <quill-editor v-model="addFormData.goods_introduce"></quill-editor>
              <el-button type="primary" class="addBtn" @click="addGood">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览窗口 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%"
    >
     <img :src="previewURL" class="preview">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: 0,
      //商品添加表单对象
      addFormData: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        //选中的商品分类
        goods_cat: [],
        //图片临时路径
        pics: [],
        //商品详情
        goods_introduce: '',
        //商品参数
        attrs:[]
        
      },
      //商品添加表单验证规则对象
      addFormDataRule: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选中商品分类", trigger: "blur" },
        ],
      },
      //商品类别列表
      cateList: [],
      //商品类别级联选择器配置
      cateListProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //获取到的商品动态参数
      params: [],
      //获取到的商品静态参数
      onlyTableData: [],
      //图片上传路径
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      //图片预览路径
      previewURL: "",
      //图片上传请求头对象
      headerObj: {
        //请求头中放入token
        Authorization: window.sessionStorage.getItem("token"),
      },
      //是否打开图片预览窗口
      previewDialogVisible: false
    };
  },
  methods: {
    //获取所有商品类别
    async queryCateList() {
      const { data: res } = await this.$http.get("/categories");
      if (res.meta.status != 200)
        return this.$message.error("商品类别列表获取失败");
      this.cateList = res.data;
      console.log(this.cateList);
    },
    //监听选中分类
    handlleChange() {
      if (this.addFormData.goods_cat.length != 3) {
        this.addFormData.goods_cat = [];
        this.$message.error("只能选中三级分类");
      }
    },
    //监听tab栏切换
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName == 0 && this.addFormData.goods_cat.length != 3) {
        this.$message.error("请先选择商品分类");
        //阻止tab栏切换
        return false;
      }
    },
    //监听tab栏的点击
    async tabclicked() {
      if (this.activeIndex == "1") {
        //发起请求，获取商品动态参数
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "many",
            },
          }
        );
        if (res.meta.status != 200)
          return this.$message.error("获取商品动态参数失败");
        //将参数标签转换为数组，方便循环
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length == 0 ? [] : item.attr_vals.split(" ");
        });
        this.params = res.data;
        console.log(this.params);
      }
      if (this.activeIndex == "2") {
        //发起请求，获取商品静态属性
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "only",
            },
          }
        );
        if (res.meta.status != 200)
          return this.$message.error("获取商品动态参数失败");

        this.onlyTableData = res.data;
        console.log(this.onlyTableData);
      }
    },
    //文件预览事件
    handlePreview(file) {
      //获取图片的绝对路径
      this.previewURL = file.response.data.url;
      //打开图片预览窗口
      this.previewDialogVisible = true
    },
    //文件移除事件
    handleRemove(file) {
      let tem_path = file.response.data.tmp_path;
      //查出删除掉的图片再表单图片数组中的索引
      let index = this.addFormData.pics.findIndex(
        (item) => item.pic == tem_path
      );
      //删除掉对应索引的项
      this.addFormData.pics.splice(index, 1);
    },
    //监听文件上传成功
    handleSuccess(response) {
      //取出响应中的信息，并将路径放入表单对象中
      const picInfo = { pic: response.data.tmp_path };
      this.addFormData.pics.push(picInfo);
    },
    //监听添加商品按钮被点击
    addGood(){
      this.$refs.addFormRef.validate(async (result) => {
        if(!result){
          return this.$message.error('请填写必要的表单')
        }
        //执行商品添加逻辑
        //lodash深拷贝一份表单数据，保证处理数据时不影响表单的动态绑定
        let formData = _.cloneDeep(this.addFormData)
        formData.goods_cat = formData.goods_cat.join(',')
        //处理动态参数
        this.params.forEach(item => {
          let newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          formData.attrs.push(newInfo)
        })
        //处理静态属性
        console.log(this.onlyTableData);
        this.onlyTableData.forEach(item => {
          let newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          formData.attrs.push(newInfo)
        })
        //发起请求添加商品
        const {data: res} = await this.$http.post('/goods',formData)
        if(res.meta.status != 201) return this.$message.error('商品添加失败！')
        this.$message.success('商品添加成功！')
        this.$router.push('/goods')
      })
    }
  },
  created() {
    //获取所有商品类别
    this.queryCateList();
  },
  computed: {
    cateId() {
      if (this.addFormData.goods_cat.length != 3) {
        return;
      } else {
        return this.addFormData.goods_cat[2];
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 15px 0 0 !important;
}
.preview{
    width: 100%;
}
.addBtn{
    margin-top: 15px;
}
</style>